package com.wrbug.mmkw.compile.generator

import com.squareup.javapoet.ClassName
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.TypeSpec
import com.youzan.router.compile.generator.Generator

import javax.annotation.processing.Filer
import javax.annotation.processing.Messager
import javax.lang.model.element.TypeElement
import javax.tools.Diagnostic

abstract class ElementGenerator(private val mFiler: Filer) : Generator {
    private var mElement: TypeElement? = null
    lateinit var className: ClassName
    fun setElement(element: TypeElement) {
        mElement = element
    }

    @Throws(Exception::class)
    abstract fun onCreateTypeSpec(element: TypeElement, className: ClassName): TypeSpec

    override fun generate() {
        val qualifiedName = mElement?.qualifiedName.toString()
        val packageName = qualifiedName.substring(0, qualifiedName.lastIndexOf("."))
        val className = qualifiedName.substring(packageName.length + 1)
        this.className = ClassName.get(packageName, className)
        try {
            val javaFile =
                JavaFile.builder(packageName, onCreateTypeSpec(mElement!!, this.className))
                    .build()
            javaFile.writeTo(mFiler)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}